package com.rxyb.sms.service.impl;

import com.rxyb.core.constants.DbConstants;
import com.rxyb.core.respone.R;
import com.rxyb.core.respone.enums.CommonCode;
import com.rxyb.sms.gateway.dto.SendSmsReq;
import com.rxyb.sms.gateway.dto.SendSmsRsp;
import com.rxyb.sms.service.SmsManageService;
import com.rxyb.sms.service.ThirdSmsRecordService;
import com.rxyb.sms.service.factory.FactoryEnum;
import com.rxyb.sms.service.factory.FactoryRoute;
import com.rxyb.sms.service.factory.SmsManagement;
import com.rxyb.sms.utils.SmsRspData;
import com.rxyb.toolize.VO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 短信发送记录 服务实现类
 * </p>
 *
 * @author DUYH
 * @since 2020-06-11
 */
@Slf4j
@Service
public class SmsManageServiceImpl implements SmsManageService {

    @Autowired(required = false)
    private FactoryRoute factoryRoute;
    @Autowired
    private ThirdSmsRecordService thirdSmsRecordService;

    @Override
    public R<SendSmsRsp> send(SendSmsReq sendSmsReq) {
        //  获取发送短信的渠道，若已选择渠道，则仅发送该渠道，若未选择渠道，则按顺序发送，直到发送成功为止
        FactoryEnum[] values;
        if (VO.isNotBlank(sendSmsReq.getEnumValue())) {
            FactoryEnum factoryEnum = FactoryEnum.from(sendSmsReq.getEnumValue());
            if (null == factoryEnum) {
                return R.failed(CommonCode.FAILED);
            }
            values = new FactoryEnum[]{factoryEnum};
        } else {
            values = FactoryEnum.values();
        }
        boolean flag = false;
        for (FactoryEnum factoryEnum : values) {
            System.out.println("begin===>" + factoryEnum.getKey());
            final SmsManagement smsManagement = factoryRoute.getFactory(factoryEnum);
            final SmsRspData smsRspData = smsManagement.send(sendSmsReq.getMobile(), sendSmsReq.getMessage());
            System.out.println("end===>" + factoryEnum.getKey());
            // 每次发送都记录入库
            thirdSmsRecordService.saveRecord(smsRspData);
            // 成功截止
            if (DbConstants.GLOBAL_STATE_SUCC.equals(smsRspData.getRspState())) {
                // 开票成功
                flag = true;
                break;
            }
        }
        if (flag) {
            return R.ok(null);
        }
        return R.failed(CommonCode.FAILED);
    }
}
